//TODO: use global oXMLHttpRequest
//var oXMLHttpRequest = null;
var MessageBundleXmlDoc = null;

function initXMLHttpRequest() 
{     
	var xhr = null;     
	
	try     
	{         
		//IE7, Firefox, Mozilla, etc.
		xhr = new XMLHttpRequest();         
		return xhr;     
	}     
	catch(e)
	{
		
	}    
	
	// IE Browsers: IE5, IE6     
	var progIDs = [ 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP' ];
	    
    for (var i = 0; i < progIDs.length; i++) 
	{
        try 
		{
            xhr = new ActiveXObject(progIDs[i]);
            return xhr;
        }
        catch (ex)
		{
        
		}
    }
	
	return xhr;
}

function loadXMLAsyn(url, response)
{

	var oXMLHttpRequest = initXMLHttpRequest();

	if (oXMLHttpRequest!=null)
	{	
			//if (oXMLHttpRequest.overrideMimeType) 
			//{
			//	oXMLHttpRequest.overrideMimeType('text/xml');
			//}
	
			//IMPORTANT:  Privileges are granted only in the scope of the requesting function
			// In Firefox, we must ask the user to grant the privileges we need to run.   
			// We need special privileges because we're talking to a web server other   
			// than the one that served the document that contains this script. 
			//UniversalXPConnect  allows us to make an XMLHttpRequest to the server, and   
			// UniversalBrowserRead allows us to look at its response.   
		
			// In IE, the user must instead enable "Access data sources across domains"   
			// in the Tools->Internet Options->Security dialog.   
			if (typeof netscape != "undefined") 
			{  
				try
				{
				//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect UniversalBrowserRead");   
				netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalFileRead");   
				}
				catch(e)
				{
					alert(e)
				}
			}  
	    
		oXMLHttpRequest.onreadystatechange = response;//function(){if(http.readyState==4){response(http)}};
		oXMLHttpRequest.open("GET",url,true);
		oXMLHttpRequest.send(null);
	}
	else
	{
		alert("Browser does not support XMLHTTP.");
	}

}


function GadgetSpecGetAsyn(url, response)
{

    loadXMLAsyn(url, response);
}

function MessageBundleGetAsyn(url, response)
{
    loadXMLAsyn(url, response);

}

function onResponse()
{	
	// 4 = "loaded"
	if(this.readyState==4)
	{
		// 200 = "OK"
		if(this.status==200)
		{
			var xmlDoc = this.responseXML; 
			var bIE = window.document.all && !window.opera;
			
			if (bIE && xmlDoc && !xmlDoc.documentElement) {
				xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.loadXML(this.responseText);
			}
			
			MessageBundleXmlDoc = xmlDoc;
            //google.language.translate(oXMLHttpRequest.responseText, "", "en", callback);

		}
		else
		{
			if (this.status==404) 
			{
				alert("URL doesn't exist!");
			}
			else
			{
				alert(this.statusText);
			}
			
		}
	}
}	



function loadXmlDocSyn(path)
{
	var xmlDoc = null;

	//Mozilla, Firefox, Opera, etc.
	if (document.implementation && document.implementation.createDocument)
	{
		var namespaceURL = "", rootTagName = "";
		
		xmlDoc = document.implementation.createDocument(namespaceURL, rootTagName, null);
		//xmlDoc.onload = testTableOutput;
		
	}// IE5+
	else if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		//xmlDoc.onreadystatechange = function() { if (xmlDoc.readyState == 4) testTableOutput() }
	
 	}
	else
	{
		alert('Your browser can\'t handle this script');
		return;
	}
	
	if (xmlDoc!=null)
	{ 
		xmlDoc.async=false;
		xmlDoc.load(path);
	}
	
	return xmlDoc;

}

function MessageBundleGetSyn(path)
{
	MessageBundleXmlDoc = loadXmlDocSyn(path);
	
}

function getMessageBundleUrls(gadgetSpec, gadgetUrl)
{
    var localeElements = gadgetSpec.documentElement.getElementsByTagName('Locale');
    var urlsArray = new Array();
	
	var index = 0;
	if(localeElements)
	{
		for(var i = 0; i <localeElements.length; i++)
		{
			
			var messages = localeElements[i].getAttribute("messages");

			if(messages != null) 
			{
				if(messages.indexOf("http")==-1)
				{	
					messages = gadgetUrl.substring(0, gadgetUrl.indexOf(".com") + 4) + messages;
				}
				
				urlsArray[index] = messages;
			    index = index + 1
				
			} 
			else
			{
						
			}
			
		}
	
	}

	return urlsArray;
}


function testTableOutput()
{
	if(MessageBundleXmlDoc!=null)
	{
		document.write("<table border='1'>");
		var x = MessageBundleXmlDoc.getElementsByTagName("msg");
		alert(x.length);

		for (i=0;i<x.length;i++)
		{  
			if(x[i].childNodes[0].nodeValue!="")
			{	
				document.write("<tr>");
				
				document.write("<td>");
				document.write(x[i].getAttribute("name"));
				document.write("</td>");
				
				document.write("<td>");
				document.write(x[i].getAttribute("name"));
				document.write("</td>");
				
				document.write("<td>");
				//x[i].text
				//x[i].firstChild.text
				document.write(x[i].childNodes[0].nodeValue);
				document.write("</td>");
				document.write("</tr>");
			}
		}
		document.write("</table>");
	}
}


 
function getGadgetLocales(gadgetSpec, url)
{

    var localeElements = gadgetSpec.documentElement.getElementsByTagName('Locale');
    var localesArray = new Array()
	
	if(localeElements)
	{
		for(var i = 0; i <localeElements.length; i++)
		{
			var lang = localeElements[i].getAttribute("lang");
			if(lang == null) lang = ""
			
			var country = localeElements[i].getAttribute("country");
			if(country == null) country = ""
			
			var messages = localeElements[i].getAttribute("messages");
			if(messages != null) 
			{
				if(messages.indexOf("http")==-1)
				{	
					messages = url.substring(0,url.indexOf(".com")+4)+messages
				}
				
			} 
			else
			{
				messages = ""
						
			}
			
			var language_direction = localeElements[i].getAttribute("language_direction");
			if(language_direction == null) language_direction = ""
			
			//alert(lang+" : "+country+" : "+" : "+messages+" : "+language_direction);
			localesArray[i] = new Locale(lang, country, messages, language_direction);
		}
	
	}

	return localesArray;
}

function getGadgetModulePrefs(gadgetSpec)
{
	
	var modulePrefs = new Object();

    var element = gadgetSpec.documentElement.getElementsByTagName('ModulePrefs')[0];
   
	if (element) 
	{
      for (var n = 0, attribute; attribute = element.attributes[n]; n++) {
        modulePrefs[attribute.name] = attribute.value;
      }
    }

	return modulePrefs;
}


function MessageBundleGetName(url)
{
	index = -1;
	index = url.lastIndexOf("/");
	var mbName = "";
	
	if(index != -1)
	{
		mbName = url.substring(index+1, url.length);
	}
	else
	{
		alert("Neispravan URL");
		
	}
	
	return mbName;
}

function MessageBundleGetLang(url)
{
  var name = MessageBundleGetName(url);
  lang = "";
  if(name.lastIndexOf('_')!=-1)
  {
	lang = name.substring(0,name.lastIndexOf('_'));
  }
  else
  {
  
  }
  return lang;
}

function MessageBundleGetCountry(url)
{
  var name = MessageBundleGetName(url);
  var country = "";
  
  if (name.lastIndexOf('_')!=-1 && name.lastIndexOf('.'))
  {
	country = name.substring(name.lastIndexOf('_')+1, name.lastIndexOf('.'));
  }
  alert("Country:"+country);
  return country;
}


function Locale(language, country, messages, language_direction )
{
	this.lang = language;
	this.country = country;
	this.messages = messages;
	this.language_direction = language_direction;


}


//TODO: private variables, better initialization of messages, optimization (ugly)
//Message Bundle: constructor
function MessageBundle(url)
{
	
	this.url = url;
	this.messages = {};
	this.descriptions = {}; //optional
	this.getFileName = function(){ return MessageBundleGetName(this.url); };	//lang_country
	this.getLang = function(){ return MessageBundleGetLang(this.url); };		//ISO639-1
	this.getCountry = function(){ return MessageBundleGetCountry(this.url); };	//ISO3166-1
	
	
}

MessageBundle.prototype.prepareContent = function(xmlDoc)
{

	var msgs = xmlDoc.getElementsByTagName("msg");
    

    
	for(var i = 0; i < msgs.length; i++)
	{
		//alert(msgs[i].firstChild.nodeValue);
		var desc = msgs[i].getAttribute("desc");
		var name = msgs[i].getAttribute("name");
		
		if(name!=null)
		{
		    if(msgs[i].firstChild!= null)
		    {
			    this.messages[name] = msgs[i].firstChild.nodeValue;
			    
			}else
			{
			    //TODO
			    this.messages[name] = "none";
			}
			
		}
		
		if(desc!=null)
		{
			alert("d");
			this.descriptions[name] = desc;
			
		}

	}
}

MessageBundle.prototype.getMessages = function()
{

    return this.messages;
}

MessageBundle.prototype.toStringNameMessagePair = function()
{
	str = this.messages.length+": ";
	for(key in this.messages)
	{
		str+=key+":"+ this.messages[key]+"\n";
	}

	alert(str)
	
	return str;
}



//mb = new MessageBundle('http://bijelizeko.googlepages.com/ALL_ALL.xml');
//mb.url = 'http://bijelizeko.googlepages.com/en_us.xml';


//MessageBundleGetAsyn('http://mychef.googlecode.com/files/ALL_ALL.xml')
//MessageBundleGetSyn('ALL_ALL.xml')




function addRow(name, message, translation)
{   
    //var container = document.firstChild.firstChild;
    var container = document.getElementById('results_translate_table');
    
    //carefull: The problem is that the Firefox DOM does not ignore line breaks and whitespaces while IE does.
    var tablebody = container.firstChild.lastChild;
    
    //Fix Bug in Mozilla: The problem is that the Firefox DOM does not ignore line breaks and whitespaces while IE does.
    //var table = getFirstChildElement(container);
    //var tablebody = getLastChildElement(table);
    
    var row = document.createElement("TR");
    
    var cellName = document.createElement("TD");
    cellName.appendChild(document.createTextNode(name));
    
    var cellMessage = document.createElement("TD");
    cellMessage.appendChild(document.createTextNode(message));
    
    var cellTranslation = document.createElement("TD");
    cellTranslation.appendChild(document.createTextNode(translation));
    
    row.appendChild(cellName);
    row.appendChild(cellMessage);
    row.appendChild(cellTranslation);
    
    tablebody.appendChild(row);
    
}


function callback(name, message, result ) 
{       
        
        if (!result.error) 
        {           
                    //translated.push(result.translation);
                     //translated[translated.length-1] = result.translation;
                   addRow(name, message, result.translation);  
				   _IG_AdjustIFrameHeight();
        } 
        else
        {
            if(result.detectedSourceLanguage)
            {
                alert("Can't translate ", result.detectedSourceLanguage);
                
            }
            else
            {
                //alert("Not supported");
            }
            addRow(name,message, "Not supported");
			_IG_AdjustIFrameHeight();
            //translated.push("Not supported");
        }

}



function createTranslationsTable(msgs, srcLang, dstLang)
{  

    var container = document.getElementById('results_translate_table');
  
    if (container.firstChild && container && container.parentNode && container.parentNode.replaceChild && container.cloneNode) 
    {  
        //container.parentNode.replaceChild(container.cloneNode(false), container);
        while (container.hasChildNodes()) 
        {
            container.removeChild(container.firstChild);
        }
    }
  
    var table = document.createElement("TABLE");
    
    var tablebody = document.createElement("TBODY");
    
    var tablehead = document.createElement("THEAD");
    
    var row = document.createElement("TR");
    
    var nameColumn = document.createElement("TH");
    nameColumn.appendChild(document.createTextNode("name"));
    
    var msgColumn = document.createElement("TH");
    msgColumn.appendChild(document.createTextNode("message"));
    
    var translationColumn = document.createElement("TH");
    translationColumn.appendChild(document.createTextNode("translation"));
    
    row.appendChild(nameColumn);
    row.appendChild(msgColumn);
    row.appendChild(translationColumn);
    
    tablehead.appendChild(row);
    
    table.appendChild(tablehead);
    table.appendChild(tablebody);

    container.appendChild(table);
    
    for(key in  msgs)
	{
        translateMessage(key, msgs[key], srcLang, dstLang);
	}
	

	
}


function translateMessage(key, msg, srcLang, dstLang)
{
    return google.language.translate(msg, srcLang, dstLang, 
	    function(result)
	    {
	        callback(key, msg, result);
	    }
	    );
}


